using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class ObstacleCon : MonoBehaviour
{
    private float _createTimer = 0f;
    private float _timer = 0f;
    private float _DestroyTime = 40f;
    private float _ObstacleCreateTime = 5f;
    private List<int> _ObstacleList = new List<int>();
    int _CreateHight;
    public GameObject _obstacle;
    // 每帧调用
    void Update()
    {
        _createTimer += Time.deltaTime;
        _timer += Time.deltaTime;
        if (_createTimer >= _ObstacleCreateTime)
        {
            if (_ObstacleList.Count < 5) 
            {
                ObstacleCreate();
                _createTimer = 0;
            }
        }
        if (_timer >= _DestroyTime) 
        {
            _ObstacleList.Clear();
            GameObject[] obj = GameObject.FindGameObjectsWithTag("Obstacle");
            for (int i = 0; i < obj.Length; i++) 
            {
                GameObject.Destroy(obj[i]);
            }
            _timer = 0;
        }
    }
    private void ObstacleCreate() 
    {
        _CreateHight = Random.Range(-6,6);
        
        while (!CanCreateHight(_ObstacleList, _CreateHight) && _ObstacleList != null)
        {
            _CreateHight = Random.Range(-6, 6);
        }
        GameObject.Instantiate(_obstacle, new Vector3(16.5f, _CreateHight, 0f), Quaternion.identity);
        _ObstacleList.Add(_CreateHight);
    }

    private bool CanCreateHight(List<int> list, int random) 
    {
        if (_ObstacleList == null) return false;
        for (int i = 0; i < list.Count; i++)
        {
            if (_ObstacleList[i] == random)
            {
                return false;
            }
        }
        return true;
    }
}
